import axios from 'axios'
import router from '@/router'
import { useUserStore } from '@/stores'

const baseURL = import.meta.env.VITE_BASE_URL

const instance = axios.create({
  baseURL,
  timeout: 10000,
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 携带token
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  (err) => Promise.reject(err),
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (!res.data.code || res.data.code === 1) {
      ElMessage.success(res.data?.msg || '操作成功')
      return res
    }
    // 处理失败的情况
    ElMessage.error(res.data.msg || '服务异常')
    return Promise.reject(res.data)
  },
  (err) => {
    if (err.response?.status === 401) {
      const userStore = useUserStore()
      userStore.removeToken()
      router.push('/login')
    }
    ElMessage.error(err.response?.data.msg || '网络异常')
    return Promise.reject(err)
  },
)

export default instance
export { baseURL }
